<template>
  <Loger ref="demensionLoger" size="big" @submit="handleSubmit" @cancel="handelCancel">
    <el-form ref="demensionFormRef" class="demension-dialog-form" :model="demensionFormData" :rules="rules" label-width="100px">
      <demension-title :has-help="false" :title="'基础信息'" />
      <el-form-item label="中文名称:" prop="nameCN"> <el-input v-model="demensionFormData.nameCN" /> </el-form-item>
      <el-form-item label="英文名称:" prop="nameEN"> <el-input v-model="demensionFormData.nameEN" /> </el-form-item>
      <el-form-item label="维度介绍:" prop="introduce">
        <el-input type="textarea" maxlength="300" :rows="3" show-word-limit v-model="demensionFormData.introduce" />
      </el-form-item>
      <el-form-item label="计算思路:" prop="train">
        <el-input type="textarea" maxlength="300" :rows="3" show-word-limit v-model="demensionFormData.train" />
      </el-form-item>
      <!-- 聚合配置 -->
      <demension-title :has-help="true" :title="'聚合配置'">
        <ul>
          <li>
            1-
            聚合是计算维度的第一步，主要是先把各个维度包含的题目进行求和或计数处理，得到一个初步的结果供后面计算结果使用。如果存在分组，则默认会对各个分组进行求和。
          </li>
          <li>2- 选项得分字段对应的是每个选项对应的得分，例如：选项A得分为1，B得分为0，则填写1,0，即得分之间以<b>英文逗号</b>分割。</li>
          <li>3- 包含题目和包含维度，仅可选择已经创建出来的选项。</li>
        </ul>
      </demension-title>
      <div class="denension-polymerize" v-for="(item, i) in demensionFormData.polymerize" :key="i">
        <span>分组{{ i + 1 }}</span>

        <el-form-item label-width="80px" label="聚合类型:">
          <el-select v-model="item.type" placeholder="请选择" style="width: 120px">
            <el-option v-for="opt in options.polymerizeType" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>

        <el-form-item label-width="80px" label="包含题目:" v-if="item.type === 'sum' || item.type === 'num'">
          <el-select v-model="item.includes" multiple collapse-tags placeholder="包含题目" style="width: 240px">
            <el-option v-for="opt in options.questions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="80px" label="选项得分:" v-if="item.type === 'sum'">
          <el-input v-model="item.fens" />
        </el-form-item>

        <el-form-item label-width="80px" label="计数选项:" v-if="item.type === 'num'">
          <el-input v-model="item.choice" />
        </el-form-item>

        <el-form-item label-width="100px" label="多维度操作:" v-if="item.type === 'include'">
          <el-select v-model="item.demensionType" placeholder="请选择" style="width: 120px">
            <el-option v-for="opt in options.demensionType" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="80px" label="包含维度:" v-if="item.type === 'include'">
          <el-select v-model="item.demensions" multiple collapse-tags placeholder="包含维度" style="">
            <el-option v-for="opt in options.demensions" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>

        <span class="polymerize-btns">
          <el-button type="danger" :icon="Minus" v-if="demensionFormData.polymerize.length > 1" @click="handleMinus(i)" />
          <el-button type="primary" :icon="Plus" @click="handleAdd" v-if="i === demensionFormData.polymerize.length - 1" />
        </span>
      </div>

      <!-- 维度结果 -->
      <demension-title :has-help="true" :title="'维度结果'">
        <ul>
          <li>1- 维度结果才是真的计算出维度的最后结果，对聚合出来的结果进行二次处理。</li>
          <li>2- 介于A|B之间的意思是，值大于A且小于等于B。</li>
          <li>3- 多个条件自上至下，逐个验证，发现满足条件则<b>不再往下继续验证</b>。</li>
        </ul>
      </demension-title>

      <el-form-item label-width="80px" label="结果类型:">
        <el-select v-model="demensionFormData.result.type" placeholder="请选择" style="width: 360px">
          <el-option v-for="opt in options.resultType" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>

      <template v-if="['norm_1', 'norm_2'].indexOf(demensionFormData.result.type) >= 0">
        <div class="denension-polymerize p16">
          <el-form-item label-width="80px" label="男A:">
            <el-input v-model="demensionFormData.result.norm.mA" />
          </el-form-item>
          <el-form-item label-width="80px" label="男B:">
            <el-input v-model="demensionFormData.result.norm.mB" />
          </el-form-item>
          <el-form-item label-width="80px" label="女A:">
            <el-input v-model="demensionFormData.result.norm.wA" />
          </el-form-item>
          <el-form-item label-width="80px" label="女B:">
            <el-input v-model="demensionFormData.result.norm.wB" />
          </el-form-item>
        </div>
      </template>

      <template v-if="demensionFormData.result.type === 'decide'">
        <div class="denension-polymerize p16" v-for="(item, i) in demensionFormData.result.decides" :key="i">
          <span>情况{{ i + 1 }}</span>
          <p v-if="item.symbol === 'in'">
            当聚合结果
            <el-select v-model="item.symbol" placeholder="请选择" style="width: 120px">
              <el-option v-for="opt in options.symbolType" :key="opt.value" :label="opt.label" :value="opt.value" />
            </el-select>
            数值
            <el-input v-model="item.val1" style="width: 60px" />
            和
            <el-input v-model="item.val2" style="width: 60px" />
            之间时，结果为
            <el-input v-model="item.result" style="width: 60px" />。
          </p>
          <p v-else-if="item.symbol === 'equal' || item.symbol === 'notequal'">
            当聚合结果
            <el-select v-model="item.symbol" placeholder="请选择" style="width: 120px">
              <el-option v-for="opt in options.symbolType" :key="opt.value" :label="opt.label" :value="opt.value" />
            </el-select>
            数值
            <el-input v-model="item.val" style="width: 60px" />
            时，结果为
            <el-input v-model="item.result" style="width: 60px" />。
          </p>
          <p v-else>类型不存在。</p>
          <span class="polymerize-btns">
            <el-button
              type="danger"
              :icon="Minus"
              v-if="demensionFormData.result.decides && demensionFormData.result.decides.length > 1"
              @click="handleResultMinus(i)"
            />
            <el-button
              type="primary"
              :icon="Plus"
              v-if="demensionFormData.result.decides && i === demensionFormData.result.decides.length - 1"
              @click="handleResultAdd"
            />
          </span>
        </div>
      </template>

      <demension-title :has-help="false" :title="'匹配报告'" />
      <div class="denension-polymerize" v-for="(item, i) in demensionFormData.reports" :key="i">
        <span>情况{{ i + 1 }}</span>
        <el-form-item label-width="50px" label="性别:">
          <el-select v-model="item.sex" placeholder="请选择" style="width: 60px">
            <el-option v-for="opt in options.sex" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label-width="50px" label="年龄:">
          <el-input v-model="item.age" style="width: 40px" />
        </el-form-item>
        <el-form-item label-width="50px" label="低分:">
          <el-input v-model="item.min" style="width: 60px" />
        </el-form-item>
        <el-form-item label-width="50px" label="高分:">
          <el-input v-model="item.max" style="width: 60px" />
        </el-form-item>
        <el-form-item label-width="50px" label="文案:">
          <el-input v-model="item.message" />
        </el-form-item>
        <span class="polymerize-btns">
          <el-button type="danger" :icon="Minus" v-if="demensionFormData.reports && demensionFormData.reports.length > 1" @click="handleReportMinus(i)" />
          <el-button type="primary" :icon="Plus" v-if="demensionFormData.reports && i === demensionFormData.reports.length - 1" @click="handleReportAdd" />
        </span>
      </div>
    </el-form>
  </Loger>
</template>

<script setup lang="ts">
  import { Http } from '@/utils/http';
  import { reactive, Ref, ref } from 'vue';
  import { Demension, Question } from '../../utils/scale.type';
  import { useMainStore } from '@/store';
  import demensionTitle from './demension-title.vue';
  import { Minus, Plus } from '@element-plus/icons-vue';
  import { OptionType } from '@/common/type';
  import { validateDemension } from '../../utils/tools';
  import Message from '@/utils/message';
  // 全局状态获取
  const mainStore = useMainStore();
  const scaleId: number = mainStore.getCurrentScale;

  // ref 获取
  const demensionLoger = ref();
  const demensionFormRef = ref();

  // 通信
  const emit = defineEmits({
    reLoad: null,
  });

  // 弹框类型
  const dialogType: Ref<string> = ref('new');

  // 表单项
  const demensionFormData = reactive<Demension>({
    // 基础信息
    nameCN: '',
    nameEN: '',
    introduce: '',
    train: '',

    // 聚合
    polymerize: [
      { type: 'sum', includes: [1, 2, 3], fens: '1,2,3' },
      { type: 'num', choice: 'A' },
    ],

    // 结果
    result: {
      type: 'return',
      decides: [{ symbol: 'in', val: '', val1: '', val2: '', result: '' }],
      norm: { mA: '', mB: '', wA: '', wB: '' },
    },

    // 报告
    reports: [{ sex: 'w', age: '12', max: 1, min: 2, message: '很好' }],
  });

  const rules = reactive({
    nameCN: [{ required: true, trigger: 'blur', message: '中文名称是必填项！' }],
    nameEN: [{ required: true, trigger: 'blur', message: '英文名称是必填项！' }],
    train: [{ required: true, trigger: 'blur', message: '思路是必填项！' }],
  });

  const options: {
    [k: string]: OptionType[];
  } = reactive({
    polymerizeType: [
      { label: '求和', value: 'sum' },
      { label: '计数', value: 'num' },
      { label: '其他维度', value: 'include' },
    ],

    demensionType: [
      { label: '求和', value: 'sum' },
      { label: '最大值', value: 'max' },
      { label: '最小值', value: 'min' },
      { label: '最大值名称', value: 'maxName' },
      { label: '最小值名称', value: 'minName' },
    ],

    resultType: [
      { label: '直接导出', value: 'return' },
      { label: '均数', value: 'average' },
      { label: '条件判断', value: 'decide' },
      { label: '公式计算: F * 20 / 10', value: 'formula_A' },
      { label: '常模计算: 50 + (10 * (F - A)) / B', value: 'norm_1' },
      { label: '常模计算: 5 + (1.5 * (F - A)) / B', value: 'norm_2' },
    ],
    symbolType: [
      { label: '介于', value: 'in' },
      { label: '等于', value: 'equal' },
      { label: '不等于', value: 'notequal' },
    ],
    symbol: [
      { label: '大于', value: '>' },
      { label: '大于且等于', value: '>=' },
      { label: '等于', value: '=' },
      { label: '小于且等于', value: '<=' },
      { label: '小于', value: '<' },
      { label: '不等于', value: '!=' },
    ],
    sex: [
      { label: '男', value: 'm' },
      { label: '女', value: 'w' },
      { label: '无', value: 'n' },
    ],

    questions: [],
    demensions: [],
  });

  // 聚合配置  增加/减少
  const handleMinus = (i: number) => {
    demensionFormData.polymerize.splice(i, 1);
  };
  const handleAdd = () => {
    demensionFormData.polymerize.push({ type: 'sum', includes: [], fens: '0,1' });
  };

  // 维度结果-情况-增加/减少
  const handleResultMinus = (i: number) => {
    demensionFormData.result.decides?.splice(i, 1);
  };
  const handleResultAdd = () => {
    demensionFormData.result.decides?.push({ symbol: 'equal', val: '1', result: '' });
  };

  // 结果匹配- 情况- 增加/减少
  const handleReportMinus = (i: number) => {
    demensionFormData.reports.splice(i, 1);
  };
  const handleReportAdd = () => {
    demensionFormData.reports.push({ sex: 'n', age: '', max: '', min: '', message: '-' });
  };

  // 确定/取消弹框
  const handleSubmit = (cb: () => void) => {
    console.log('🚀 ~ file: demension-dialog.vue ~ line 277 ~ handleSubmit ~ demensionFormRef.value', JSON.parse(JSON.stringify(demensionFormRef.value)));
    demensionFormRef.value.validate((v: boolean) => {
      if (v) {
        const secondValidate = validateDemension(demensionFormData);

        if (secondValidate.isValidate) {
          console.log('校验通过！');
        } else {
          Message.warning(secondValidate.msg);
        }
        return false;
        let url = `/demension/${dialogType.value === 'new' ? 'create' : 'update'}`;
        Http.post(url, { ...demensionFormData, ...{ scaleId } }).then(() => {
          emit('reLoad');
        });
        cb();
      }
    });
  };
  const handelCancel = (cb: () => void) => {
    demensionFormRef.value.resetFields();
    cb();
  };

  /**
   * 弹框打开方法：使用传参来渲染弹框
   * @param title string
   * @param type 'new' | 'edit'
   * @param qt Question
   */
  const open = (title: string, type: 'new' | 'edit', { questions, demensions }: { questions: Question[]; demensions: Demension[] }, d?: Demension) => {
    console.log('🚀 ~ file: demension-dialog.vue ~ line 329 ~ open ~ questions', questions);
    console.log('🚀 ~ file: demension-dialog.vue ~ line 329 ~ open ~ demensions', demensions);
    demensionLoger.value.open(title);
    dialogType.value = type;

    options.questions = questions?.map((item) => ({ label: item.idx + '.' + item.title, value: item.idx }));
    options.demensions = demensions?.map((item) => ({ label: item.nameCN + '[' + item.nameEN + ']', value: item.nameEN }));

    if (type === 'edit') {
      demensionFormData.id = d?.id;
    }
  };

  // 对外暴露属性/方法
  defineExpose({
    open,
  });
</script>

<style scoped lang="scss">
  .demension-dialog-form {
    padding: 0 40px;
  }
  .demension-title {
    font-weight: bold;
    position: relative;
    padding-left: 10px;
    height: 32px;
    line-height: 32px;
    background: #eee;
    margin-bottom: 10px;

    &::after {
      content: '';
      position: absolute;
      height: 14px;
      width: 3px;
      background: #21e;
      left: 0;
      top: 9px;
    }
  }

  .denension-polymerize {
    &.p16 {
      padding-bottom: 16px;
    }
    display: flex;
    span {
      width: 50px;
      line-height: 32px;
      color: gray;
      flex: none;
      padding-left: 10px;
    }
    .polymerize-btns {
      width: 84px;

      button {
        width: 32px;
        margin-top: -1px;
      }
    }
  }
</style>
